﻿using System.Data;
using System.IO;
using OfficeOpenXml;

namespace DevelopTool.Common
{
    /// <summary>
    /// Excel帮助类
    /// </summary>
    public static class ExcelHelper
    {
        /// <summary>
        /// DataTable导出为excel
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="filePath"></param>
        /// <param name="sheetName"></param>
        public static void ExportToExcel(DataTable dataTable,string filePath,string sheetName = "Sheet1")
        {
            using(ExcelPackage excelPackage = new ExcelPackage())
            {
                ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add(sheetName);
                
                // 将DataTable的数据导入到Excel中
                worksheet.Cells["A1"].LoadFromDataTable(dataTable,true);

                // 保存文件
                FileInfo excelFile = new FileInfo(filePath);
                excelPackage.SaveAs(excelFile);
            }
        }

    }
}
